﻿using HDS.Data;
using HDS.IService.Master;
using HDS.Model;
using HDS.Model.Entity.Master;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace HDS.Service.Master
{
    public class ExchangeRateService : IExchangeRateService
    {
        private MasterDbContext db = new MasterDbContext();

        public async Task<ExchangeRate> Get(string codeFrom, string codeTo)
        {
            return await db.ExchangeRate.GetSingleAsync(e => e.CodeFrom.Equals(codeFrom) && e.CodeTo.Equals(codeTo));
        }

        public async Task<DataPagingModel<ExchangeRate>> GetList(Expression<Func<ExchangeRate, bool>> whereExpression, int pageIndex = 1, int pageSize = 20)
        {
            RefAsync<int> total = 0;
            var rows = await db.Db.Queryable<ExchangeRate>().WhereIF(whereExpression != null, whereExpression).ToPageListAsync(pageIndex, pageSize, total);
            return new DataPagingModel<ExchangeRate>
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageTotal = (total.Value + pageSize - 1) / pageSize,
                Total = total.Value,
                Rows = rows
            };
        }

        public async Task Update(ExchangeRate entity)
        {
            var old = await db.ExchangeRate.GetSingleAsync(e => e.CodeFrom.Equals(entity.CodeFrom) && e.CodeTo.Equals(entity.CodeTo));
            if (old == null)
            {
                await db.ExchangeRate.InsertAsync(entity);
            }
            else
            {
                await db.Db.Updateable(entity).ExecuteCommandAsync();
            }
        }

        public async Task Delete(string CodeFrom, string CodeTo)
        {
            await db.ExchangeRate.DeleteAsync(e => e.CodeFrom.Equals(CodeFrom) && e.CodeTo.Equals(CodeTo));
        }
    }
}
